package com.bobamrz.frontend;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * @author Vladimir Morozov
 *
 */
public class AddToClipboardAjaxServlet extends SecuredSuperServlet {

	private static final long serialVersionUID = -2984347123174468315L;
	private Logger log = Logger.getLogger(AddToClipboardAjaxServlet.class);

	@Override
	protected void securedGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.debug("adding to clipboard");
		String id = req.getParameter("id");
		if(id == null || id.equals("")){
			throw new InvalidParameterException();
		} 
		Long docId = Long.parseLong(id);
		
		HttpSession session = req.getSession(false);
		@SuppressWarnings("unchecked")
		List<Long> docIdsInClipboard = (List<Long>)session.getAttribute("clipboard");
		
		if(docIdsInClipboard == null) {
			log.debug("clipboard empty, creating");
			docIdsInClipboard = new ArrayList<Long>();
			session.setAttribute("clipboard", docIdsInClipboard);
		}
		
		if(!docIdsInClipboard.contains(docId)) {
			docIdsInClipboard.add(docId);
			log.debug("added");
		} else {
			log.debug("document is already in clipboard");
		}
		
		
	}
}
